<?php

namespace app\controller;

use app\BaseController;

use app\model\admin\SysUser;
use app\model\admin\SysLoginLog;
use app\model\admin\SysMember;
use app\service\JwtAuth;
use app\utils\captcha\CaptchaApi;
use think\Request;
use app\service\SysUserService;
use think\facade\Db;
use app\service\MemberService;

class Auth extends BaseController
{
    public function login(Request $request)
    {
        $params = $request->post();

        $username = $params['username'] ?? '';
        $password = $params['password'] ?? '';
        $user_type = $params['user_type'] ?? 'admin';
        $captcha_key = $params['uuid'] ?? '';
        $captcha = $params['code'] ?? '';


        if (!$captcha_key) {
            return error('缺少必要参数[captcha_key]');
        }
        if (!$captcha) {
            return error('缺少必要参数[captcha]');
        }
        $check_captcha = CaptchaApi::check($captcha_key, $captcha);
        if (!env('APP_DEBUG') && $check_captcha == false) {
            return error('验证码错误');
        }


        // if ($user_type == 'admin') {
        //     $user = SysUser::where('username', trim($username))->find();
        // } elseif ($user_type == 'user') {
        //     // todo
        // } else {
        //     return error('登录参数有误');
        // }
        if ($user_type == 'admin') {
            $user = SysUser::where('username', trim($username))->find();
            if ($user) {
                Db::table('sys_user')->where('id', $user->id)->update([
                    "login_ip" => $request->ip()
                ]);
            } else {
                return error('管理员身份的用户名不存在');
            }
        } elseif ($user_type == 'user') {
            $user = SysMember::where('username', trim($username))->find();
            if ($user) {
                Db::table('member_user')->where('id', $user->id)->update([
                    "login_ip" => $request->ip()
                ]);
            } else {
                return error('商户身份的用户名不存在');
            }
        } else {
            return error('登录参数有误');
        }

        if ($user == null) {
            return $this->loginLog($username, '用户不存在');
        }
        if ($user->password != md5($password)) {
            return $this->loginLog($username, '密码不正确');
        }

        $ret = [
            'token' => JwtAuth::createToken($user->id, $user_type)
        ];
        $ret = array_merge($ret, $user->toArray());

        if (isset($params['password'])) {
            $params['password'] = '******';
        }
        if ($user_type == 'user') {
            // admin不记录
            SysLoginLog::create([
                'username' => $username,
                'login_ip' => $request->ip(),
                'user_id' => $user->id,
                'request_param' => json_encode($params),
                'remark' => '登录成功',
                'user_type' => $user_type
            ]);
        }

        return success($ret, '登录成功');
    }
    /**
     * 获取登录信息
     * 返回用户信息(角色，权限，个人信息)
     */
    public function getInfo(Request $request)
    {
        // $auth_info = $request->authInfo;

        // $user_id = $auth_info['user_id'];
        // $user_type = $auth_info['user_type'];


        // if ($user_type == 'admin') {
        //     return SysUserService::getInfo($user_id);
        // } elseif ($user_type == 'user') {
        //     // todo
        // } else {
        //     return error('未知用户类型');
        // }
        // return error('未知错误');
        $auth_info = $request->authInfo;

        $user_id = $auth_info['user_id'];
        $user_type = $auth_info['user_type'];

        if ($user_type == 'admin') {
            return SysUserService::getInfo($user_id);
        } elseif ($user_type == 'user') {
            return MemberService::getInfo($user_id);
        } else {
            return error('未知用户类型');
        }

        return error('未知错误[getInfo]');
    }

    /**
     * 获取登录用户路由信息(后台菜单)
     */
    public function getRouters(Request $request)
    {
        $auth_info = $request->authInfo;

        $user_id = $auth_info['user_id'];
        $user_type = $auth_info['user_type'];

        if ($user_type == 'admin') {
            $menus_routes = SysUserService::getRouters($user_id);
        } elseif ($user_type == 'user') {
            // $menus_routes = [];
            $menus_routes = MemberService::getRouters($user_id);
        } else {
            return error('未知用户类型');
        }
        return success($menus_routes);
    }

    public function logout(Request $request)
    {
        # code...
        return success([]);
    }
    protected function loginLog($username, $msg)
    {
        $param = request()->param();

        SysLoginLog::create([
            'username' => $username,
            'login_ip' => request()->ip(),
            'user_id' => 0,
            'request_param' => json_encode($param),
            'remark' => $msg,
        ]);
        return error($msg);
    }
}
